const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("opendb-city-china");
const $ = db.command.aggregate;
module.exports = class PayService extends Service {
  async payIntegral(){
		const ctx=this.ctx
		const time=(new Date()).getTime()
		const transaction = await db.startTransaction()
		try{
			const res=await transaction.collection('uni-id-base-order').doc(ctx.data.order_id).get()
			const res1=await transaction.collection('uni-id-users').doc(ctx.uid).get()
			if(res1.affectedDocs==0||res.affectedDocs==0){
				await transaction.rollback()
				return response.fail('订单错误')
			}
			//uniCloud.logger.log(res1)
			if(res1.data.integral<res.data.total_fee){
				await transaction.rollback()
				return response.fail('积分不足')
			}
			const res2=await transaction.collection('uni-id-base-order').doc(ctx.data.order_id).update({
				status:2,
				update_time:time,
				paid_time:time
			})
			//uniCloud.logger.log(res2)
			const res3=await transaction.collection('uni-id-scores').add({
				user_id:ctx.uid,
				type:2,
				create_date:time,
				comment:'商品购买',
				score:res.data.total_fee
			})
			const res4=await transaction.collection('uni-id-users').doc(ctx.uid).update({
				integral:dbCmd.inc(-res.data.total_fee)
			})
			//uniCloud.logger.log(res3)
			for(let i=0;i<res.data.sku_ids.length;i++){
				const sku=await transaction.collection('opendb-mall-sku').doc(res.data.sku_ids[i]).get()
				if(sku.affectedDocs>0&&sku.data.stock>=res.data.counts[i]){
					await transaction.collection('opendb-mall-sku').doc(res.data.sku_ids[i]).update({
						stock:dbCmd.inc(-res.data.counts[i])
					})
				}else{
					await transaction.rollback()
					return response.fail('库存不足')
				}
			}
			if(res2.affectedDocs>0&&res3.id&&res4.affectedDocs>0){
				await transaction.commit()
				return response.success('ok')
			}else{
				await transaction.rollback()
				return response.fail('事物回滚')
			}
		}catch(e){
			await transaction.rollback()
			uniCloud.logger.log(`transaction error`, e)
			return response.fail(JSON.stringify(e));
		}
		
  }
};